package com.example.mobile1931605061xhj0604;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MusicService extends Service {
    String TAG = "TAG";
    MediaPlayer player;

    class Service extends Binder {
        public MusicService getMusicService() {
            return MusicService.this;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(getApplicationContext(), R.raw.music);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: 在启动命令上");
        playMusic();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onStartCommand: 绑定时");
        return new Service();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: 解除绑定时");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        stopMusic();
        Log.i(TAG, "onDestroy: 摧毁");
        super.onDestroy();
    }

    public void playMusic() {
        player = MediaPlayer.create(getApplicationContext(), R.raw.music);
        player.start();
    }
    public void stopMusic() {
        if (player != null && player.isPlaying()) {
            player.stop();
            player.release();
            player = null;
        }
    }
}
